﻿using ConsoleHoster.ViewModel;
using System.IO;
using System.Windows.Forms;

namespace ConsoleHoster.View.Controls
{
	/// <summary>
	/// Interaction logic for ProjectDetailsView.xaml
	/// </summary>
	public partial class ProjectDetailsView : System.Windows.Controls.UserControl
	{
		public ProjectDetailsView()
		{
			InitializeComponent();

			this.tbaExecutable.ButtonAction = () => this.ChooseExecutable();
			this.tbaWorkingDir.ButtonAction = () => this.ChooseWorkingDirectory();
		}

		private void ChooseExecutable()
		{
			string tmpExecutable = this.ViewModel.Project.Executable;
			using (OpenFileDialog tmpOpenFile = new OpenFileDialog())
			{
				tmpOpenFile.Multiselect = false;
				tmpOpenFile.InitialDirectory = Path.GetDirectoryName(tmpExecutable);
				tmpOpenFile.Filter = "All files|*.*";

				DialogResult tmpDialogResult = tmpOpenFile.ShowDialog();
				if (tmpDialogResult == System.Windows.Forms.DialogResult.OK)
				{
					this.ViewModel.Project.Executable = tmpOpenFile.FileName;
					this.ViewModel.Project.WorkingDir = Path.GetDirectoryName(tmpExecutable);
				}
			}
		}

		private void ChooseWorkingDirectory()
		{
			using (FolderBrowserDialog tmpDialog = new FolderBrowserDialog())
			{
				if (this.ViewModel.Project.Executable != null)
				{
					tmpDialog.SelectedPath = Path.GetPathRoot(this.ViewModel.Project.Executable);
				}

				DialogResult tmpResult = tmpDialog.ShowDialog();
				if (tmpResult == System.Windows.Forms.DialogResult.OK)
				{
					this.ViewModel.Project.WorkingDir = tmpDialog.SelectedPath;
				}
			}
		}

		private ProjectDetailsViewModel ViewModel
		{
			get
			{
				return this.DataContext as ProjectDetailsViewModel;
			}
		}
	}
}
